<?php
namespace app\api\controller;

use addons\third\model\Third;
use app\admin\enum\CouponGetType;
use app\admin\model\Auditlog;
use app\admin\model\CouponRecord;
use app\admin\model\Details;
use app\common\controller\Api;
use fast\Http;
use think\Db;

class Wechat extends Api
{
    protected $noNeedLogin = ['code', 'login','getWxcode'];
    protected $noNeedRight = ['*'];
    protected $appid;
    protected $secret;
    protected $loginUrl;

    public function __construct()
    {
        $this->appid = get_addon_config("loginmobile")['appId'];
        $this->secret = get_addon_config("loginmobile")['secretId'];
        $this->loginUrl = get_addon_config("loginmobile")['loginUrl'];
        parent::__construct();
    }

    //https://hongqi-b.maoln.com/api/Auth_login_with_wechat/test

    /**
     * 登录第一步，获取openid 跟 session_key
     */
    public function code()
    {
        $code = $this->request->param('code');
        if (!$code) {
            $this->error('code不能为空');
        }
        self::getOpenid($code);
    }


    /**
     * @param $code 用来交换获取openid 跟 session_key
     */
    public function getOpenid($code)
    {
        $url = sprintf($this->loginUrl, $this->appid, $this->secret, $code);
        $result = Http::get($url);
        $wxResult = json_decode($result, true);
        if (empty($wxResult)) {
            $this->error('获取sessin_key及openID时异常');
        }
        if (isset($wxResult['errcode']) && $wxResult['errcode'] != 0) {
            $this->error($wxResult['errmsg']);
        }
        $item = [
            'openid' => $wxResult['openid'],
            'session_key' => $wxResult['session_key']
        ];
        return $item;
    }


    /**
     * 用户登录
     */
    public function login()
    {
        $encryptedData = $this->request->post('encryptedData');
        $code = $this->request->post('code');
        $pid = $this->request->post('pid');
        $iv = $this->request->post('iv');
        $code_info = $this->getOpenid($code);
        $openid = $code_info['openid'];

        $userinfo = \app\admin\model\User::where(['openid' => $openid])->find();
        if ($userinfo) {
            if($userinfo['status']!='normal'){
                $this->error('该账户已停用');
            }
            if($userinfo['role']!='user'){
                $details =Details::where('user_id','=',$userinfo['id'])->where('login_status','=','正常')->find();
                if(!$details){
                    $this->error('该身份已停用');
                }
            }
            $this->auth->direct($userinfo['id']);
        } else {
            $user = new \app\admin\model\User();
            $user->data([
                'openid' => $openid,
                'pid' => $pid == "" ? '0' : $pid,
                'status' => 'normal',
                'jointime' =>time(),
            ]);
            $user->save();
            $this->auth->direct($user->id);
            //获取优惠券
          $coupon=\app\admin\model\Coupon::where('coupon_type','=',2)->where('status','=',1)->select();
          if($coupon!=null){
              foreach ($coupon as $k => $v) {
                  CouponRecord::create( [
                      'coupon_id'   => $v['id'],
                      'user_id'     => $user->id,
                      'type'        => $v['type'],
                      'name'        => $v['name'],
                      'money'       => $v['money'],
                      'min_money'   => $v['min_money'],
                      'expire_time' => $v['expire_day'] * 86400 + time(),
                      'status'      => 0,
                      'get_type'    => CouponGetType::ASSIGN,
                      'coupon_type'=>$v['coupon_type']
                  ]);
              }
          }
        }

        $phone_user = \app\admin\model\User::get($this->auth->id);
        //获取手机号
        $errCode = self::decryptData($encryptedData, $iv, $data, $code_info['session_key'], $this->appid);
        if ($errCode == 0) {
            $result = json_decode($data, true);
            if (isset($result['phoneNumber'])) {

                if($phone_user['mobile']==""||$phone_user['mobile']==null){
                    $mobile= \app\admin\model\User::where('mobile','=',$result['phoneNumber'])->find();
                    if($mobile){
                        $this->error('该手机号已存在');
                    }
                }
                if($phone_user['role']=='user'){
                    //匹配身份
                    $pd=Details::Where('phone','=',$result['phoneNumber'])
                        ->whereNull('user_id')
                        ->find();
                    if($pd){
                        Details::Where('id','=',$pd['id'])
                            ->Update(['user_id'=>$phone_user['id']]);
                        $add['role']=$pd['role'];
                        $role = \app\admin\model\User::where('id','=',$pd['applicant_id'])->value('role');
                        if($role=='room'){
                            $add['room_id']=$pd['applicant_id'];
                        }else{
                            $add['agent_id']=$pd['applicant_id'];
                        }
                    }
                }
                $add['mobile']=$result['phoneNumber'];
                \app\admin\model\User::where('id','=',$phone_user['id'])->update($add);
                $this->success('获取成功', $result);
            } else {
                $this->error('号码获取失败');
            }
        }


        $token = $user['token'] = $this->auth->getToken();
        $this->success('登录成功', ['token' => $token, 'user' => $this->auth->getUserinfo()]);

    }

    /**
     * 获取手机号
     */
    public function getPhone($iv,$encryptedData,$code)
    {
        $datainfo = $this->auth->getUserinfo();
        $user = \app\admin\model\User::get($datainfo['id']);

        $code_info = $this->getOpenid($code);
        $errCode = self::decryptData($encryptedData, $iv, $data, $code_info['session_key'], $this->appid);
        if ($errCode == 0) {
            $result = json_decode($data, true);
            if (isset($result['phoneNumber'])) {

                if($user['mobile']==""||$user['mobile']==null){
                    $mobile= \app\admin\model\User::where('mobile','=',$result['phoneNumber'])->find();
                    if($mobile){
                        $this->error('该手机号已存在');
                    }
                }
                if($user['role']=='user'){
                    //匹配身份
                    $pd=Details::Where('phone','=',$result['phoneNumber'])
                        ->whereNull('user_id')
                        ->find();
                    if($pd){
                        Details::Where('id','=',$pd['id'])
                            ->Update(['user_id'=>$user['id']]);
                        $user->role=$pd['role'];
                        $role = \app\admin\model\User::where('id','=',$pd['applicant_id'])->value('role');
                        if($role=='room'){
                            $user->room_id=$pd['applicant_id'];
                        }else{
                            $user->agent_id=$pd['applicant_id'];
                        }
                    }
                }
                $user->mobile = $result['phoneNumber'];
                $user->save();
                $this->success('获取成功', $result);
            } else {
                $this->error('号码获取失败');
            }
        } else {
            $this->error('用户信息更新失败');
        }
    }


    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData($encryptedData, $iv, &$data, $sessionKey, $appid)
    {
        if (strlen($sessionKey) != 24) {
            return -41001;
        }
        $aesKey = base64_decode($sessionKey);


        if (strlen($iv) != 24) {
            return -41002;
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            return -41003;
        }
        if ($dataObj->watermark->appid != $appid) {
            return -41003;
        }
        $data = $result;
        return 0;
    }

    public function getWxAccessToken() {

        $appid =  $this->appid;
        $appsecret = $this->secret;

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
        $access_token = makeRequest($url);
        $access_token = json_decode($access_token['result'], true);

        return $access_token;
    }


    //获取二维码
    public function getWxcode($uid) {
        $ACCESS_TOKEN = $this->getWxAccessToken();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $ACCESS_TOKEN['access_token'];
        $post_data =
            array(
                'page' => 'pages/index/index',
                'scene' => $uid,
                'check_path'=>false,
                'env_version'=>'trial'
            );
        $post_data = json_encode($post_data);
        $data = send_post($url, $post_data);
        return  data_uri($data, 'image/png');



    }


}